#!/usr/bin/env ruby
require File.dirname(__FILE__) + '/../../lib/pop_ssl'
require File.dirname(__FILE__) + '/../../config/environment'
require 'mime/types'
require 'tmail'

logger = Logger.new("#{RAILS_ROOT}/log/receive_email.log")


def parse_email(email)
  evalmail = TMail::Mail.parse(email)
  if evalmail.from[0] == "open@movilforum.com" 
    comment = evalmail.body.split("\r\nTexto:")
    #quien lo manda
    who = comment[0].sub("Movil:","")
    message = comment[1].split(" ")
    
    # comentario de evento
    if message[0].downcase.index('eve')==0
      event = message[0].sub("EVE", '')
      event = message[0].sub("eve", '')
      message.slice!(0)
      message = message.join(" ")
      puts "evento: " + event
      puts "mensaje: " + message
      create_comment(who, message, event)
    end
    
    # petición de datos
    if message[0].downcase.index('detalles')==0
      event = message[0].downcase.sub("detalles ", '')
      deteiled_event = Event.find(event)
      Notifier.deliver_event_info(who, deteiled_event)
      puts "enviando detalles del evento: " + event
    end
  else
    event = evalmail.subject
    puts event
    evalmail.attachments.each do |attachment|
      evimg = EventImage.new(:uploaded_data => attachment)
      evimg.event_id = event
      evimg.save
    end
  end
end

def create_comment(who, message, event)
  Comment.create!(:sender => who,
                  :message => message,
                  :event_id => event)
end

def mail_settings
  @mail_settings ||= YAML.load_file(RAILS_ROOT + '/config/mail.yml') rescue {}
end

puts mail_settings['host']

puts "Echándole un vistazo al correo:::" + Time.now.to_s
Net::POP3.enable_ssl(OpenSSL::SSL::VERIFY_NONE)
Net::POP3.start(mail_settings['host'], mail_settings['port'].to_i, mail_settings['account_login'], mail_settings['account_password']) do |pop|
  if pop.mails.empty?
    puts "Ni un correo, no tienes amigos" 
  else
    pop.mails.each do |email|
      begin
        puts "descargando correo" 
        parse_email(email.pop)
      rescue Exception => e
        puts "Error " + Time.now.to_s + "::: " + e.message
      end
    end
  end
end
puts "Ya, hasta la próxima" + Time.now.to_s


